import os
from PySide6.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QWidget
from PySide6.QtCore import Qt, QEventLoop
from PySide6.QtGui import QKeyEvent, QPixmap
from api import api
from common import config

class BaseDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
    
    def create_button_layout(self, save_callback):
        """创建统一的按钮布局"""
        button_layout = QHBoxLayout()
        
        cancel_btn = QPushButton("取消")
        cancel_btn.setObjectName("cancelButton")
        cancel_btn.clicked.connect(self.reject)
        
        save_btn = QPushButton("提交")
        save_btn.setObjectName("saveButton")
        save_btn.clicked.connect(save_callback)
        
        button_layout.addWidget(cancel_btn)
        button_layout.addWidget(save_btn)
        
        return button_layout

class MessageBox(QDialog):
    def __init__(self, title, message, msg_type='info', parent=None):
        super().__init__(parent)
        self.setWindowTitle(title)
        self.setFixedSize(400, 200)
        self.setModal(True)
        
        # 创建布局
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建图标和消息区域的水平布局
        content_layout = QHBoxLayout()
        
        # 设置图标
        icon_label = QLabel()
        icon_size = 32
        icon_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources', 'icons')
        
        if msg_type == 'error':
            icon_file = os.path.join(icon_path, 'error.svg')
            button_object_name = 'errorButton'
        elif msg_type == 'warning':
            icon_file = os.path.join(icon_path, 'warning.svg')
            button_object_name = 'warningButton'
        elif msg_type == 'question':
            icon_file = os.path.join(icon_path, 'question.svg')
            button_object_name = 'questionButton'
        else:  # info
            icon_file = os.path.join(icon_path, 'info.svg')
            button_object_name = 'infoButton'
        
        icon_label.setPixmap(QPixmap(icon_file).scaled(icon_size, icon_size, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        content_layout.addWidget(icon_label, 1)
        
        # 创建消息标签
        message_label = QLabel(message)
        message_label.setObjectName("messageLabel")
        message_label.setWordWrap(True)
        content_layout.addWidget(message_label, 9)
        #content_layout.addStretch()
        
        layout.addLayout(content_layout)
        layout.addStretch()

        # 添加取消按钮
        if msg_type == 'question':
            cancel_button = QPushButton("取消")
            cancel_button.setObjectName("cancelButton")
            cancel_button.clicked.connect(self.reject)
            layout.addWidget(cancel_button)
        
        # 添加确定按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        ok_button = QPushButton("确定")
        ok_button.setObjectName(button_object_name)
        ok_button.clicked.connect(self.accept)
        button_layout.addWidget(ok_button)
        
        layout.addLayout(button_layout)
    
    @staticmethod
    def error(title, message, parent=None):
        dialog = MessageBox(title, message, 'error', parent)
        return dialog.exec_()
    
    @staticmethod
    def warning(title, message, parent=None):
        dialog = MessageBox(title, message, 'warning', parent)
        return dialog.exec_()
    
    @staticmethod
    def info(title, message, parent=None):
        dialog = MessageBox(title, message, 'info', parent)
        return dialog.exec_()
    
    @staticmethod
    def question(title, message, parent=None):
        dialog = MessageBox(title, message, 'question', parent)
        return dialog.exec_()

class MessageOverlay(QWidget):
    ACCEPTED = 0
    REJECTED = 1
    CLOSED = 2

    def __init__(self, parent, message_type="info", message_text=""):
        super().__init__(parent)
        self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
        self.setGeometry(parent.rect())

        self.message_type = message_type
        self.message_text = message_text
        self._result = MessageOverlay.CLOSED
        self._loop = QEventLoop()
        self.init_ui()

    def init_ui(self):
        self.box = QWidget(self)
        self.box.setFixedSize(300, 180)
        self.box.setObjectName("contentBox")
        self.box.move((self.width() - self.box.width()) // 2,
                      (self.height() - self.box.height()) // 2)

        icon_label = QLabel()
        icon_label.setFixedSize(32, 32)

        type_config = {
            "info": ("ℹ️", "info"),
            "warning": ("⚠️", "warning"),
            "error": ("❌", "error"),
            "question": ("❓", "question")
        }

        emoji, objectName = type_config.get(self.message_type, ("ℹ️", "info"))
        icon_label.setText(emoji)
        icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        icon_label.setObjectName(objectName)

        text_label = QLabel(self.message_text)
        text_label.setWordWrap(True)
        text_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        text_label.setObjectName("messageText")

        layout = QVBoxLayout(self.box)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.addWidget(icon_label, alignment=Qt.AlignmentFlag.AlignCenter)
        layout.addSpacing(10)
        layout.addWidget(text_label)
        layout.addStretch()

        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(15)
        ok_btn = QPushButton("确定")
        ok_btn.setObjectName(objectName)
        ok_btn.clicked.connect(self.accept)
        btn_layout.addWidget(ok_btn)
        if self.message_type == "question":
            cancel_btn = QPushButton("取消")
            cancel_btn.setObjectName("cancel")
            cancel_btn.clicked.connect(self.reject)
            btn_layout.addWidget(cancel_btn)

        layout.addLayout(btn_layout)
    
    def exec(self):
        self.show()
        lastbtn = list(self.findChildren(QPushButton))[-1]
        lastbtn.setFocus()
        self._loop.exec()
        return self._result

    def accept(self):
        self._result = MessageOverlay.ACCEPTED
        self._loop.quit()
        self.close()

    def reject(self):
        self._result = MessageOverlay.REJECTED
        self._loop.quit()
        self.close()

    def closeEvent(self, event):
        # 如果用户直接关闭遮罩窗口
        if self._loop.isRunning():
            self._result = MessageOverlay.CLOSED
            self._loop.quit()
        event.accept()

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key.Key_Return or event.key() == Qt.Key.Key_Enter:
            lastbtn = list(self.findChildren(QPushButton))[-1]
            lastbtn.click()
        else:
            super().keyPressEvent(event)

    @staticmethod
    def info(parent, message):
        dialog = MessageOverlay(parent, "info", message)
        return dialog.exec()
    
    @staticmethod
    def warning(parent, message):
        dialog = MessageOverlay(parent, "warning", message)
        return dialog.exec()
    
    @staticmethod
    def error(parent, message):
        dialog = MessageOverlay(parent, "error", message)
        return dialog.exec()
    
    @staticmethod
    def question(parent, message):
        dialog = MessageOverlay(parent, "question", message)
        return dialog.exec()        
